package com.cweb.admin.model.wx.wx_mp_user_info.service;

import com.cweb.framework.base.serivce.BaseMybatisService;
import com.cweb.framework.pojo.CustomException;
import com.cweb.admin.model.wx.wx_mp_user_info.entity.WxMpUserInfo;
import com.cweb.admin.model.wx.wx_mp_user_info.mapper.WxMpUserInfoMapper;
import com.cweb.admin.serivce.wxMp.WeixinMpSerivce;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * 微信-公众号用户信息 服务实现类
 *
 * @since 2020-08-14
 */
@Service
public class WxMpUserInfoService extends BaseMybatisService<WxMpUserInfoMapper, WxMpUserInfo> {

    @Autowired
    private WeixinMpSerivce weixinMpSerivce;

    /**
     * 保存相关用户信息
     */
    @Async
    public void saveUserInfoAync(Long platformId, String openid) throws CustomException {
        Integer count = this.getBaseMapper().countByOpenid(openid);
        if (count > 0) {
            return;
        }
        // 取得用户信息
        WxMpUser wxMpUser = weixinMpSerivce.getUserInfo(platformId, openid);
        // 保存信息
        WxMpUserInfo wxMpUserInfo = new WxMpUserInfo();
        wxMpUserInfo.setOpenid(openid); // openid
        wxMpUserInfo.setNickname(wxMpUser.getNickname()); // 昵称
        wxMpUserInfo.setSex(wxMpUser.getSex()); // 性别
        wxMpUserInfo.setProvince(wxMpUser.getProvince()); // 省份
        wxMpUserInfo.setCity(wxMpUser.getCity()); // 城市
        wxMpUserInfo.setCountry(wxMpUser.getCountry()); // 国家
        wxMpUserInfo.setHeadimgurl(wxMpUser.getHeadImgUrl()); // 用户头像
        wxMpUserInfo.setPrivilege(StringUtils.join(wxMpUser.getPrivileges(), ",")); // 用户特权信息
        wxMpUserInfo.setUnionid(wxMpUser.getUnionId()); // 绑定关系
        this.save(wxMpUserInfo);
    }
}
